#!/usr/bin/env python
# Prototype code for IRC based Lua to TNS converter

import os
import urllib2
import tempfile
import subprocess
import shutil, glob

import source_dict

# Get variables from dict!
ONLINE_PASTEBIN_LOOKUP = source_dict.get_pastebin()

global GID
GID = 0

# Functions
def stop():
	#raw_input()
	blabla = 1
	
def printl(thestr=""):
	global GID, LUAPROJDIR
	print "[Job "+str(GID)+"] "+thestr
	try:
		fh_log = open(os.path.join(LUAPROJDIR, "lua2tnslog.txt"), "a")
		fh_log.write(thestr+"\n")
		fh_log.close()
	except IOError,e:
		print "ERROR: Couldn't write to log file! Reason: "+str(e)

def compile_file(id, src, target):
	global GID, LUAPROJDIR
	FAIL_CODE = 0
	GID = 0
	GID = id
	TARGET_FILE = target
	ONLINE_SOURCE = src
	
	OLD_DIR = os.getcwd()
	
	LUAPROJDIR = tempfile.mkdtemp("", "luaproj_")
	
	# OK, let's actually find it.
	FINAL_PICK = ""
	FINAL_PICK_INDEX = 0
	#for SITEARRAY in ONLINE_PASTEBIN_LOOKUP_NOREP:
	for SITEARRAY in ONLINE_PASTEBIN_LOOKUP:
		printl("Searching for string "+SITEARRAY[0]+" in URL...")
		if ONLINE_SOURCE.find(SITEARRAY[0]) != -1:
			FINAL_PICK = SITEARRAY[0]
			break
		FINAL_PICK_INDEX = FINAL_PICK_INDEX + 1
	# If nothing was found, assume that this is a direct URL.
	if FINAL_PICK == '':
		printl("No match - assuming that this is a direct URL.")
		FINAL_URL = ONLINE_SOURCE
	else:	
		printl("Found string "+FINAL_PICK+" in URL...")
		stop()
		
		# Now take the index and look up the definition.
		DEF_SPLIT = ONLINE_PASTEBIN_LOOKUP[FINAL_PICK_INDEX][1].split("@@ONLINE_ID@@")
		if len(DEF_SPLIT) == 2:
			if DEF_SPLIT[0] == "":
				# The online ID is at the beginning
				ONLINE_ID = ONLINE_SOURCE[7:ONLINE_SOURCE.find(ONLINE_PASTEBIN_LOOKUP[FINAL_PICK_INDEX][0])]
			else:
				# The online ID is at the end
				ONLINE_ID = ONLINE_SOURCE[ONLINE_SOURCE.find(ONLINE_PASTEBIN_LOOKUP[FINAL_PICK_INDEX][0])+len(ONLINE_PASTEBIN_LOOKUP[FINAL_PICK_INDEX][0]):]
		elif len(DEF_SPLIT) == 3:
			ONLINE_ID = ONLINE_SOURCE[len(DEF_SPLIT[0]):][:ONLINE_SOURCE[len(DEF_SPLIT[0]):].find(DEF_SPLIT[2])]
		
		# WOW... that was intense stuff. Let's see if everything came out OK...
		printl("Final online ID: "+ONLINE_ID)
		stop()
	
		# Not too bad, eh? Let's go ahead and get the final URL! :D
		FINAL_URL = ONLINE_PASTEBIN_LOOKUP[FINAL_PICK_INDEX][2].replace("@@ONLINE_ID@@", ONLINE_ID)
	
	printl("Final URL: "+FINAL_URL)
	stop()
	
	# Grab online source!
	try:
		LUAFILEN = tempfile.mkstemp(".lua", "tmp", LUAPROJDIR)[1]
		LUAFILE = open(LUAFILEN, "w")
		grabconn = urllib2.urlopen(FINAL_URL)
		LUAFILE.write(grabconn.read())
		grabconn.close()
		LUAFILE.close()
	except urllib2.HTTPError, e:
		printl("ERROR: Couldn't get the file! Blame it on HTTP Error Code "+str(e.code)+"! :P")
		#exit(1)
		FAIL_CODE = 1
		return [FAIL_CODE, LUAPROJDIR]
	except urllib2.URLError, e:
		printl("ERROR: Cannot retrieve URL: " + str(e.reason[1]))
		#exit(1)
		FAIL_CODE = 1
		return [FAIL_CODE, LUAPROJDIR]
	
	printl("Saved Lua source file to: "+LUAFILEN)
	stop()
	
	# Great! Now we need to parse the other fun options - building ones, in particular.
	
	# Sanity checks!
	CHECKPATH = LUAPROJDIR + "/" + TARGET_FILE
	if os.path.abspath(CHECKPATH) != CHECKPATH:
		print "Hacking attempt!"
		print "Typed path is "+CHECKPATH
		print "Absolute path is "+os.path.abspath(CHECKPATH)
		printl("Invalid file name!")
		#exit(1)
		FAIL_CODE = 1
		return [FAIL_CODE, LUAPROJDIR]
	
	# Build the command!
	CMD = "./luna " + LUAFILEN + " " + os.path.join(LUAPROJDIR, TARGET_FILE)
	
	printl("Final converting command: "+CMD)
	stop()
	
	# Copy all necessary files to the temp dir!
	printl("Copying any needed assembler binaries...")
	printl("Copying Luna binary to "+LUAPROJDIR+"...")
	shutil.copy('luna', LUAPROJDIR)
	
	# Execute the command!
	printl("Running command...")
	#os.chdir(LUAPROJDIR)
	printl("DEBUG: subprocess arg is "+str(CMD.split(" ")))
	LUA_PROC = subprocess.Popen(CMD.split(" "), shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
	LUA_OUTPUT = LUA_PROC.stdout.read()
	LUA_ERRCODE = LUA_PROC.wait()
	printl("Output:")
	printl(LUA_OUTPUT)
	printl("Error code: "+str(LUA_ERRCODE))
	FAIL_CODE = LUA_ERRCODE
	stop()
	
	# We're done!
	printl("That's all! :D")
	stop()
	
	#os.chdir(OLD_DIR)
	
	return [FAIL_CODE, LUAPROJDIR, os.path.join(LUAPROJDIR, TARGET_FILE)]
	
